package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    Configuration configuration;
    @Autowired
    AuthorMapper authorMapper;
    @Autowired
    @Qualifier("minIOFileStorageService")
    FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    String prefix;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1.获取template模板对象
            Template template = configuration.getTemplate("article.ftl");

            //2.准备替换模板的数据（作者对应apUser id ，文章信息apArticle ，文章详情 content）
            Map params = new HashMap<>();
            //文章内容
            params.put("content", JSON.parseArray(content,Map.class));
            //文章信息
            params.put("article", apArticle);
            //作者对应的app账户id
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            params.put("authorApUserId",apAuthor.getUserId());

            //3.基于数据替换模板  得到输出内容  静态页
            StringWriter writer = new StringWriter();
            template.process(params,writer);
            String htmlStr = writer.toString();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(htmlStr.getBytes());

            //4.将得到的静态页面，上传到minio中

            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);

            //5.将上传的minio文件路径   设置到 ap_Article 中的 static_url字段上
            apArticle.setStaticUrl(store);

            apArticleMapper.updateById(apArticle);
            log.info("成功生成文章的静态页  静态页地址 ：{}",readPath+store);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成文章的静态页失败  失败原因 ：{}",e.getCause());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页面异常，失败原因 {}"+e.getCause());

        }
    }
}
